import React, { useState } from 'react';
import { Form, Input, Button, Tabs, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import './index.scss';
// import { login } from '../../utils/request';
import { fetchLogin } from '../../store/modules/userStore'; 
import { useDispatch } from 'react-redux';

const { TabPane } = Tabs;

const LoginRegisterForm = () => {
  const [isAdmin, setIsAdmin] = useState(false);
  const [formType, setFormType] = useState('login');
  const [loading, setLoading] = useState(false); // 
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const onFinish = async (values) => {
  try {
    // 1. 设置加载状态
    setLoading(true);
    console.log('登录数据:', values);
    
    // 2. 准备登录数据
    const loginInfo = {
      username: values.username.trim(), // 去除前后空格
      password: values.password,
      role: isAdmin ? 'admin' : 'user'
    };
    console.log('登录数据:', loginInfo);
    // 3. 发起登录请求
    const result = await dispatch(fetchLogin(loginInfo)).unwrap();
    console.log(loginInfo.role);
    
    
    // 4. 处理成功响应
    message.success('登录成功');
    console.log('登录结果:', result);
    
    // 5. 根据角色跳转
    const redirectPath = result.redirectUrl || (isAdmin ? '/adminbookMg' : '/');
    navigate(redirectPath, {
      replace: true // 替换当前历史记录
    });
    
  } catch (error) {
    // 6. 错误处理
    console.error('登录失败:', error);
    message.error(
      error.message || 
      (error.response?.data?.message || '登录失败，请检查账号密码')
    );
  } finally {
    // 7. 重置加载状态
    setLoading(false);
    }
  };

  return (
    <div className='login-container'> 
      <div className='login-register-container'>
        <Tabs
          defaultActiveKey="user"
          onChange={(key) => setIsAdmin(key  === 'admin')}
        >
          <TabPane tab="用户登入" key="user" />
          <TabPane tab="管理员登入" key="admin" />
        </Tabs>
        <Form onFinish={onFinish}>
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名或邮箱' },
            ]}
          >
            <Input placeholder="用户名/邮箱" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
            ]}
          >
            <Input.Password placeholder="密码" />
          </Form.Item>
          {!isAdmin && formType === 'register' && (
            <Form.Item
              name="phone"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' },
              ]}
            >
              <Input placeholder="手机号" />
            </Form.Item>
          )}
          <div>
            <Button type="primary" htmlType="submit">
              {formType === 'login' ? '登录' : '注册'}
            </Button> 
            {!isAdmin && (
              <Button
                type="link"
                onClick={() => setFormType(formType === 'login' ? 'register' : 'login')}
                style={{ visibility: isAdmin ? 'hidden' : 'visible' }}
              >
                {formType === 'login' ? '去注册' : '去登录'}
              </Button>
            )}
          </div>
        </Form>
      </div>
    </div>
  );
};

export default LoginRegisterForm;